<template>
  <GenericTableManager
    title="角色管理"
    @search="handleSearch"
    @add="handleAdd"
    @edit="handleEdit"
    @delete="handleDelete"
    @export="handleExport"
    @import="handleImport"
    @refresh="handleRefresh"
    @submit="handleSubmit"
    @selection-change="handleSelectionChange"
    ref="tableManagerRef"
  >
    <!-- 搜索表单插槽 -->
    <template #search="{ searchForm, handleSearch, handleReset, loading }">
      <el-form :model="searchForm" :inline="true" @submit.prevent="handleSearch">
        <el-form-item label="角色名称">
          <el-input
            v-model="searchForm.roleName"
            placeholder="请输入角色名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="正常" value="0" />
            <el-option label="停用" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch" :loading="loading">搜索</el-button>
          <el-button :icon="Refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </template>

    <!-- 操作按钮插槽 -->
    <template #actions="{ handleAdd, handleExport, handleImport, handleRefresh, selectedRows, loading }">
      <el-button type="primary" :icon="Plus" @click="handleAdd">新增角色</el-button>
      <el-button type="success" :icon="Download" @click="handleExport" :loading="loading">导出</el-button>
      <el-button type="warning" :icon="Upload" @click="handleImport" :loading="loading">导入</el-button>
      <el-button v-if="selectedRows.length > 0" type="danger" :icon="Delete" @click="handleBatchDelete">批量删除</el-button>
    </template>

    <!-- 表格列插槽 -->
    <template #columns="{ tableData, handleEdit, handleDelete }">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="roleId" label="角色ID" width="80" />
      <el-table-column prop="roleName" label="角色名称" width="150" />
      <el-table-column prop="roleKey" label="权限字符" width="150" />
      <el-table-column prop="roleSort" label="显示顺序" width="100" />
      <el-table-column prop="dataScope" label="数据范围" width="120">
        <template #default="{ row }">
          <el-tag :type="getDataScopeType(row.dataScope)">
            {{ getDataScopeText(row.dataScope) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="80">
        <template #default="{ row }">
          <el-tag :type="row.status === '0' ? 'success' : 'danger'">
            {{ row.status === '0' ? '正常' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="160" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" :icon="Edit" @click="handleEdit(row)">编辑</el-button>
          <el-button type="success" size="small" :icon="Key" @click="handleAuth(row)">分配权限</el-button>
          <el-button type="danger" size="small" :icon="Delete" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </template>

    <!-- 表单插槽 -->
    <template #form="{ formData, formRules, formRef, isEdit, loading }">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="formData.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="权限字符" prop="roleKey">
          <el-input v-model="formData.roleKey" placeholder="请输入权限字符" />
        </el-form-item>
        <el-form-item label="显示顺序" prop="roleSort">
          <el-input-number v-model="formData.roleSort" :min="0" style="width: 100%" />
        </el-form-item>
        <el-form-item label="数据范围" prop="dataScope">
          <el-select v-model="formData.dataScope" style="width: 100%">
            <el-option label="全部数据权限" value="1" />
            <el-option label="自定数据权限" value="2" />
            <el-option label="本部门数据权限" value="3" />
            <el-option label="本部门及以下数据权限" value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
    </template>
  </GenericTableManager>

  <!-- 权限分配对话框 -->
  <el-dialog
    v-model="authDialogVisible"
    title="分配权限"
    width="800px"
    :close-on-click-modal="false"
  >
    <el-tree
      ref="menuTreeRef"
      :data="menuTreeData"
      :props="{ children: 'children', label: 'title' }"
      show-checkbox
      node-key="id"
      :default-checked-keys="checkedKeys"
      check-strictly
    />
    <template #footer>
      <el-button @click="authDialogVisible = false">取消</el-button>
      <el-button type="primary" :loading="authLoading" @click="handleAuthSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Download, Upload, Edit, Key, Delete } from '@element-plus/icons-vue'
import GenericTableManager from '@/components/GenericTableManager.vue'
import { useRoleTableManager } from '@/composables/useTableManager'
import { businessValidationRules } from '@/utils/commonValidation'
import { roleApiManager } from '@/api/common'
import type { Role, MenuTreeNode } from '@/types/system'

// 使用通用表格管理
const {
  tableData,
  loading,
  pagination,
  searchForm,
  selectedRows,
  handleSearch,
  handleReset,
  handleAdd,
  handleEdit,
  handleDelete,
  handleBatchDelete,
  handleSubmit,
  handleExport,
  handleImport,
  handleRefresh,
  handleSelectionChange,
  setFormRules,
  setSearchForm
} = useRoleTableManager()

// 表格管理器引用
const tableManagerRef = ref()

// 权限分配相关
const authDialogVisible = ref(false)
const authLoading = ref(false)
const menuTreeData = ref<MenuTreeNode[]>([])
const checkedKeys = ref<number[]>([])
const menuTreeRef = ref()
const currentRole = ref<Role | null>(null)

// 设置表单验证规则
const formRules = businessValidationRules.role.form()

// 初始化
onMounted(() => {
  setFormRules(formRules)
  setSearchForm({
    roleName: '',
    status: ''
  })
})

// 获取数据范围类型
const getDataScopeType = (dataScope: string) => {
  const types: { [key: string]: 'success' | 'primary' | 'warning' | 'info' | 'danger' } = {
    '1': 'success',
    '2': 'warning',
    '3': 'info',
    '4': 'primary'
  }
  return types[dataScope] || 'info'
}

// 获取数据范围文本
const getDataScopeText = (dataScope: string) => {
  const texts: { [key: string]: string } = {
    '1': '全部数据权限',
    '2': '自定数据权限',
    '3': '本部门数据权限',
    '4': '本部门及以下数据权限'
  }
  return texts[dataScope] || '未知'
}

// 分配权限
const handleAuth = async (row: Role) => {
  currentRole.value = row
  authDialogVisible.value = true
  
  try {
    // 模拟获取菜单数据
    menuTreeData.value = [
      {
        id: 1,
        title: '系统管理',
        children: [
          { id: 11, title: '用户管理' },
          { id: 12, title: '角色管理' },
          { id: 13, title: '菜单管理' }
        ]
      },
      {
        id: 2,
        title: '系统监控',
        children: [
          { id: 21, title: '在线用户' },
          { id: 22, title: '登录日志' }
        ]
      }
    ]
    
    // 模拟获取已选中的权限
    checkedKeys.value = [11, 12]
  } catch (error) {
    ElMessage.error('获取权限数据失败')
  }
}

// 权限分配提交
const handleAuthSubmit = async () => {
  try {
    authLoading.value = true
    
    // 获取选中的权限
    const checkedNodes = menuTreeRef.value?.getCheckedKeys() || []
    
    // 模拟提交权限分配
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('权限分配成功')
    authDialogVisible.value = false
  } catch (error) {
    ElMessage.error('权限分配失败')
  } finally {
    authLoading.value = false
  }
}
</script>

<style scoped lang="scss">
// 样式已由 GenericTableManager 组件提供
</style>
